package com.ai.deepseekspring.service.impl;




import com.ai.deepseekspring.Enum.ResponseEnum;
import com.ai.deepseekspring.Result.R;
import com.ai.deepseekspring.service.VectorService;
import com.ai.deepseekspring.utils.RequestUtil;
import com.ai.deepseekspring.utils.TokenUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.ai.document.Document;
import org.springframework.ai.vectorstore.SearchRequest;
import org.springframework.ai.vectorstore.VectorStore;
import org.springframework.ai.vectorstore.filter.Filter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;


@Service
public class VectorServiceImpl implements VectorService {

    private static final Logger log = LoggerFactory.getLogger(VectorServiceImpl.class);

    @Autowired
    private VectorStore vectorStore;

    @Override
    public R add(String content) {
        try {
            if (content == null || content.isBlank()) {
                return R.error(ResponseEnum.ERROR);
            }
            String userId = TokenUtil.parseToken(RequestUtil.getTokenFromHeader()).get("id").toString();
            Document doc = createUserDocument(content, userId);
            vectorStore.add(List.of(doc));
            return R.ok(ResponseEnum.SUCCESS);
        } catch (Exception e) {
            log.warn("vector add failed, err={}", e.toString());
            return R.error(ResponseEnum.ERROR);
        }
    }

    @Override
    public R delete() {
        try {
            String userId = TokenUtil.parseToken(RequestUtil.getTokenFromHeader()).get("id").toString();
            Filter.Expression filterExpr = new Filter.Expression(
                    Filter.ExpressionType.EQ, new Filter.Key("userId"), new Filter.Value(userId));
            vectorStore.delete(List.of(userId));
            return R.ok(ResponseEnum.SUCCESS);
        } catch (Exception e) {
            log.warn("vector delete failed, err={}", e.toString());
            return R.error(ResponseEnum.ERROR);
        }
    }

    @Override
    public List<?> find(String content) {
        String userId = TokenUtil.parseToken(RequestUtil.getTokenFromHeader()).get("id").toString();
        try {
            if (content == null || content.isBlank()) {
                return Collections.emptyList();
            }

            Filter.Expression filterExpr = new Filter.Expression(
                    Filter.ExpressionType.EQ, new Filter.Key("userId"), new Filter.Value(userId));

            SearchRequest sr = SearchRequest.builder()
                    .query(content)
                    //.filterExpression(filterExpr)
                    .topK(5)                  // 控制返回数量
                    .similarityThreshold(0.0) // 不设阈值屏蔽
                    .build();

            List<?> hits = vectorStore.similaritySearch(sr);

            // 若为 0，可选：去掉过滤再次探测，便于定位（仅日志，不改变返回值）
            if (hits.isEmpty()) {
                SearchRequest probe = SearchRequest.builder()
                        .query(content).topK(3).similarityThreshold(0.0).build();
                List<?> probeHits = vectorStore.similaritySearch(probe);
                log.debug("vector probe(no filter) size={}, userId={}, query='{}'", probeHits.size(), userId, content);
            }
            System.out.println(hits);
            return hits;
        } catch (Exception e) {
            log.warn("vector find failed, content='{}', err={}", content, e.toString());
            return Collections.emptyList();
        }
    }

    private Document createUserDocument(String content, String userId) {
        Map<String, Object> metadata = new HashMap<>();
        metadata.put("userId", userId);       // 关键：与过滤键一致
        metadata.put("source", "user_input");
        return new Document(UUID.randomUUID().toString(), content, metadata);
    }
}




